package com.ssyc.gsk_master.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ssyc.common.base.AppManager;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.manager.ARouterUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.CacheDataManager;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.AlertDialogUtil;
import com.ssyc.common.utils.ExitLoginUtil;
import com.ssyc.common.utils.NotificationsUtils;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.gsk_master.R;
import com.suke.widget.SwitchButton;

/**
 * 我的Fragment
 * Created by Administrator on 2018/6/12 0012.
 */

public class MasterMeFragment extends LazyBaseFragment implements View.OnClickListener, SwitchButton.OnCheckedChangeListener {
    private SwitchButton switchNoticeButton;
    //缓存大小的文本
    private TextView tvCachSize;
    private RelativeLayout llClean;
    private RelativeLayout llStrategy;
    private RelativeLayout llOut;
    private RelativeLayout rl_gywm;
    private RelativeLayout rl_zxzh;
    //隐私政策
    private RelativeLayout rl_yszc;
    //用户协议
    private RelativeLayout rl_yhxy;

    //加载框
    private RelativeLayout rlLoading;

    //内容布局
    private LinearLayout llContent;

    //头像
    private RoundedImageView ivHead;

    //姓名
    private TextView tvName;

    //账号
    private TextView tv_acc;

    //是否需要跳转通知界面的标识
    private boolean isNeeded = true;

    public static final String TAG = MasterMeFragment.class.getName();

    //单体模式
    private static class LazyHolder {
        private static final MasterMeFragment INSTANCE = new MasterMeFragment();
    }

    public static final MasterMeFragment newInstance() {
        return LazyHolder.INSTANCE;
    }


    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.master_fragment_me;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);
        showContent();

        //初始化视图
        initView(view);

        //请求页面数据
        http();
    }


    /**
     * 初始化视图
     */
    public void initView(View view) {
        switchNoticeButton = view.findViewById(R.id.switch_notice_button);
        tvCachSize = view.findViewById(R.id.tv_cach_size);
        llClean = view.findViewById(R.id.ll_clean);
        llClean.setOnClickListener(this);
        llStrategy = view.findViewById(R.id.ll_strategy);
        llStrategy.setOnClickListener(this);
        llOut = view.findViewById(R.id.ll_out);
        llOut.setOnClickListener(this);
        ivHead = view.findViewById(R.id.iv_head);
        tvName = view.findViewById(R.id.tv_name);
        rlLoading = view.findViewById(R.id.rl_loading);
        llContent = view.findViewById(R.id.ll_content);
        rlLoading.setVisibility(View.VISIBLE);
        llContent.setVisibility(View.GONE);
        rl_gywm = view.findViewById(R.id.rl_gywm);
        rl_gywm.setOnClickListener(this);
        rl_zxzh = view.findViewById(R.id.rl_zxzh);
        rl_zxzh.setOnClickListener(this);

        rl_yszc = view.findViewById(R.id.rl_yszc);
        rl_yszc.setOnClickListener(this);

        rl_yhxy = view.findViewById(R.id.rl_yhxy);
        rl_yhxy.setOnClickListener(this);

        tv_acc = view.findViewById(R.id.tv_acc);

        ImageUtil.displayImage(getActivity(), ivHead, AccountUtils.getIcon(getActivity()), R.drawable.base_default_head);


        tvName.setText(AccountUtils.getName(getActivity()));
        tv_acc.setText(AccountUtils.getAccount(getActivity()));

    }

    /**
     * 请求页面数据
     */
    private void http() {
        rlLoading.setVisibility(View.GONE);
        llContent.setVisibility(View.VISIBLE);

        //设置默认的缓存大小
        initState();
    }


    /**
     * 设置初始状态
     */
    private void initState() {

        //设置显示缓存大小的TextView
        try {
            if (CacheDataManager.getTotalCacheSize(getContext()).startsWith("0.0")) {
                tvCachSize.setText("(0.00M)");
            } else {
                tvCachSize.setText("(" + CacheDataManager.getTotalCacheSize(getContext()) + ")");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        switchNoticeButton.setOnCheckedChangeListener(this);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        if (!isDoubleClick(view)) {

            int id = view.getId();
            if (id == R.id.ll_clean) {
                //清除缓存
//                showCleanPop();
                showCleanCachePop();
            } else if (id == R.id.ll_strategy) {
                //攻略
                ARouter.getInstance().build("/teacher/TeacherStrategyActivity").navigation();

            } else if (id == R.id.ll_out) {
                //退出登录
                showExitPop();

            } else if (id == R.id.rl_gywm) {
                //关于我们
                ARouter.getInstance().build("/main/AboutUsActivity").navigation();
            } else if (id == R.id.rl_zxzh) {
                //注销用户
                doAnsubscribeAction();
            } else if (id == R.id.rl_yszc) {
                //隐私政策
                ARouter.getInstance().build("/main/AgreementAndPrivacyActivity").withString("title", "隐私政策").navigation();
            } else if (id == R.id.rl_yhxy) {
                //用户协议
                ARouter.getInstance().build("/main/AgreementAndPrivacyActivity").withString("title", "用户协议").navigation();
            }


        }
    }

    /**
     * 开关按钮的监听事件
     *
     * @param view
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {

        //点关闭时,这个时候通知状态是true,开关状态是false   切回来的时候通知状态还是true,开关状态同步为true
        if (isChecked == NotificationsUtils.isOpenNotification(getContext())) {
            isNeeded = false;
        } else {
            isNeeded = true;
        }

        if (isNeeded) {
            //需要跳转界面
            NotificationsUtils.startSysSettingActivity(getContext());
        }
    }


    /**
     * 弹出清除缓存的弹框
     */
    private void showCleanPop() {
        try {
            if (CacheDataManager.getTotalCacheSize(getContext()).startsWith("0.0")) {
                //证明无缓存需要清理
                UIHelper.showToast(getContext(), "暂无缓存需要清理");
                return;
            } else {

                AlertDialogUtil.showAlertDialog(true, getContext(), "确定清除所有本地缓存吗?", new AlertDialogUtil.onListener() {
                    @Override
                    public void onClickOk() {
                        //清除缓存
                        cleanCache();
                    }

                    @Override
                    public void onClickDismiss() {

                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 弹出退出登录的弹框
     */
    private void showExitPop() {

//        AlertDialogUtil.showAlertDialog(true, getContext(), "确定退出吗?", new AlertDialogUtil.onListener() {
//            @Override
//            public void onClickOk() {
//                //退出学生端的相关操作,清空SP的相关数据
//                ExitLoginUtil.exitLogin(getContext());
//
//                //跳转到角色选择界面
//                ARouterUtils.start("/main/ChooseRoleActivity");
//                AppManager.getInstance().removeOthers();
//            }
//
//            @Override
//            public void onClickDismiss() {
//
//            }
//        });

        //弹框
        PopUpManager.showPopByMatchParent(getContext(), R.layout.base_pop_exit_sys, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                TextView tv_again = view.findViewById(R.id.tv_again);
                TextView tv_over = view.findViewById(R.id.tv_over);
                tv_again.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //取消
                            PopUpManager.dismiss();
                        }

                    }
                });

                tv_over.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //退出的相关操作,清空SP的相关数据
                            ExitLoginUtil.exitLogin(getContext());

                            //跳转到角色选择界面
                            ARouterUtils.start("/main/ChooseRoleActivity");
                            AppManager.getInstance().removeOthers();

                            //关闭弹框
                            PopUpManager.dismiss();
                        }

                    }
                });
            }
        });


    }


    /**
     * 清除缓存
     */
    private void showCleanCachePop() {
        PopUpManager.showPopByMatchParent(getContext(), R.layout.base_pop_clean_caches, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                TextView tv_again = view.findViewById(R.id.tv_again);
                TextView tv_over = view.findViewById(R.id.tv_over);
                tv_again.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //取消
                            PopUpManager.dismiss();
                        }

                    }
                });

                tv_over.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //确定
                            PopUpManager.dismiss();
                            //清除缓存
                            cleanCache();
                        }

                    }
                });

            }
        });
    }

    /**
     * 注销用户的操作
     */
    private void doAnsubscribeAction() {
        PopUpManager.showPopByMatchParent(getContext(), R.layout.com_pop_unsubscribe, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {

            }
        });
    }


    /**
     * 清除缓存的方法
     */
    private void cleanCache() {
        new Thread(new clearCache()).start();
    }


    /**
     * 处理清除缓存消息的Handler对象
     */
    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:

                    UIHelper.showToast(getContext(), "清除缓存成功");

                    try {
                        if (CacheDataManager.getTotalCacheSize(getContext()).startsWith("0.0")) {
                            tvCachSize.setText("(0.00M)");
                        } else {
                            tvCachSize.setText("( " + CacheDataManager.getTotalCacheSize(getContext()) + " )");
                        }

                    } catch (Exception e) {

                        e.printStackTrace();
                    }

                    break;
            }
        }
    };


    /**
     * 实现清除缓存的Runnable
     */
    class clearCache implements Runnable {

        @Override

        public void run() {

            try {

                CacheDataManager.clearAllCache(getContext());

                Thread.sleep(300);

                if (CacheDataManager.getTotalCacheSize(getContext()).startsWith("0")) {

                    handler.sendEmptyMessage(0);

                }

            } catch (Exception e) {

                return;

            }

        }

    }


    /**
     * 同步通知开关的状态
     */
    private void sycSwitchState() {
        if (NotificationsUtils.isOpenNotification(getContext())) {
            //开启了通知权限
            switchNoticeButton.setChecked(true);
        } else {
            switchNoticeButton.setChecked(false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        sycSwitchState();
    }


    @Override
    public void onDestroy() {
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

}
